<template>
  <div>
    <h2>Email Templates</h2>
    
    <div class="action-buttons">
      <el-button type="primary" @click="showAddDialog">Create Template</el-button>
    </div>
    
    <!-- Email Templates Table -->
    <el-table :data="templates" style="width: 100%; margin-top: 20px;" v-loading="loading">
      <el-table-column prop="id" label="ID" width="80"></el-table-column>
      <el-table-column prop="templateName" label="Name" width="200"></el-table-column>
      <el-table-column prop="subject" label="Subject" width="250"></el-table-column>
      <el-table-column prop="description" label="Description"></el-table-column>
      <el-table-column label="Actions" width="200">
        <template slot-scope="scope">
          <el-button size="mini" @click="handlePreview(scope.row)">Preview</el-button>
          <el-button size="mini" type="primary" @click="handleEdit(scope.row)">Edit</el-button>
          <el-button size="mini" type="danger" @click="handleDelete(scope.row)">Delete</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <!-- Pagination -->
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="currentPage"
      :page-sizes="[10, 20, 50, 100]"
      :page-size="pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      style="margin-top: 20px;">
    </el-pagination>
    
    <!-- Add/Edit Dialog -->
    <el-dialog :title="dialogTitle" :visible.sync="formDialogVisible" width="800px">
      <el-form :model="form" :rules="rules" ref="form" label-width="120px">
        <el-form-item label="Template Name" prop="templateName">
          <el-input v-model="form.templateName" placeholder="Enter template name"></el-input>
        </el-form-item>
        <el-form-item label="Subject" prop="subject">
          <el-input v-model="form.subject" placeholder="Enter email subject"></el-input>
        </el-form-item>
        <el-form-item label="Description">
          <el-input v-model="form.description" placeholder="Enter template description"></el-input>
        </el-form-item>
        <el-form-item label="Content" prop="content">
          <el-input v-model="form.content" type="textarea" :rows="10" placeholder="Enter email content (HTML supported)"></el-input>
          <div class="el-form-item__tip">
            Use {{variable}} syntax for variables. Example: Hello {{name}}
          </div>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="formDialogVisible = false">Cancel</el-button>
        <el-button type="primary" @click="submitForm">Save</el-button>
      </span>
    </el-dialog>
    
    <!-- Preview Dialog -->
    <el-dialog title="Template Preview" :visible.sync="previewDialogVisible" width="800px">
      <div v-if="selectedTemplate">
        <h3>{{ selectedTemplate.templateName }}</h3>
        <p><strong>Subject:</strong> {{ selectedTemplate.subject }}</p>
        
        <div class="template-editor">
          <h4>Test Variables</h4>
          <el-form :inline="true">
            <el-form-item v-for="(value, key) in testVariables" :key="key" :label="key">
              <el-input v-model="testVariables[key]" @input="applyTestVariables"></el-input>
            </el-form-item>
          </el-form>
        </div>
        
        <div class="template-preview">
          <h4>Preview</h4>
          <div>
            <strong>Subject:</strong> {{ previewSubject }}
          </div>
          <div class="content-preview" v-html="previewContent"></div>
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="previewDialogVisible = false">Close</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'EmailTemplates',
  data() {
    return {
      templates: [],
      loading: false,
      currentPage: 1,
      pageSize: 10,
      total: 0,
      formDialogVisible: false,
      previewDialogVisible: false,
      dialogTitle: 'Create Email Template',
      isEdit: false,
      form: {
        id: null,
        templateName: '',
        subject: '',
        content: '',
        description: ''
      },
      rules: {
        templateName: [
          { required: true, message: 'Please enter template name', trigger: 'blur' }
        ],
        subject: [
          { required: true, message: 'Please enter email subject', trigger: 'blur' }
        ],
        content: [
          { required: true, message: 'Please enter email content', trigger: 'blur' }
        ]
      },
      selectedTemplate: null,
      testVariables: {},
      previewSubject: '',
      previewContent: ''
    };
  },
  created() {
    this.loadTemplates();
  },
  methods: {
    loadTemplates() {
      this.loading = true;
      this.$axios.get(`/email-templates?page=${this.currentPage}&size=${this.pageSize}`)
        .then(response => {
          this.templates = response.data.records;
          this.total = response.data.total;
          this.loading = false;
        })
        .catch(error => {
          console.error('Error loading templates:', error);
          this.$message.error('Failed to load email templates');
          this.loading = false;
        });
    },
    
    handleSizeChange(size) {
      this.pageSize = size;
      this.loadTemplates();
    },
    
    handleCurrentChange(page) {
      this.currentPage = page;
      this.loadTemplates();
    },
    
    showAddDialog() {
      this.dialogTitle = 'Create Email Template';
      this.isEdit = false;
      this.form = {
        id: null,
        templateName: '',
        subject: '',
        content: '',
        description: ''
      };
      this.formDialogVisible = true;
    },
    
    handleEdit(row) {
      this.dialogTitle = 'Edit Email Template';
      this.isEdit = true;
      this.form = { ...row };
      this.formDialogVisible = true;
    },
    
    handleDelete(row) {
      this.$confirm('Are you sure you want to delete this template?', 'Warning', {
        confirmButtonText: 'Yes',
        cancelButtonText: 'No',
        type: 'warning'
      }).then(() => {
        this.$axios.delete(`/email-templates/${row.id}`)
          .then(() => {
            this.$message.success('Template deleted successfully');
            this.loadTemplates();
          })
          .catch(error => {
            console.error('Error deleting template:', error);
            this.$message.error('Failed to delete template');
          });
      }).catch(() => {
        // User cancelled
      });
    },
    
    submitForm() {
      this.$refs.form.validate(valid => {
        if (valid) {
          if (this.isEdit) {
            // Update existing template
            this.$axios.put(`/email-templates/${this.form.id}`, this.form)
              .then(() => {
                this.$message.success('Template updated successfully');
                this.formDialogVisible = false;
                this.loadTemplates();
              })
              .catch(error => {
                console.error('Error updating template:', error);
                this.$message.error('Failed to update template');
              });
          } else {
            // Add new template
            this.$axios.post('/email-templates', this.form)
              .then(() => {
                this.$message.success('Template created successfully');
                this.formDialogVisible = false;
                this.loadTemplates();
              })
              .catch(error => {
                console.error('Error creating template:', error);
                this.$message.error('Failed to create template');
              });
          }
        }
      });
    },
    
    handlePreview(template) {
      this.selectedTemplate = template;
      this.previewSubject = template.subject;
      this.previewContent = template.content;
      
      // Extract variables from template
      this.testVariables = {};
      const variableRegex = /{{(.*?)}}/g;
      let match;
      
      while ((match = variableRegex.exec(template.subject + template.content)) !== null) {
        const variable = match[1].trim();
        if (!this.testVariables[variable]) {
          this.testVariables[variable] = variable;
        }
      }
      
      this.previewDialogVisible = true;
    },
    
    applyTestVariables() {
      if (!this.selectedTemplate) return;
      
      let subject = this.selectedTemplate.subject;
      let content = this.selectedTemplate.content;
      
      // Replace variables in subject and content
      for (const [key, value] of Object.entries(this.testVariables)) {
        const regex = new RegExp(`{{${key}}}`, 'g');
        subject = subject.replace(regex, value);
        content = content.replace(regex, value);
      }
      
      this.previewSubject = subject;
      this.previewContent = content;
    }
  }
}
</script>
